//
//  HESocketManager.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/11/27.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HESocketManager.h"
#import "HEIMInfoEntity.h"
#import "HEIMForward.h"
#import "HEDocImMsgModel.h"


@interface HESocketManager ()


@property (nonatomic, strong) SocketManager *manger;
 
@property (nonatomic, strong) NSPointerArray *delegateList;

@end

@implementation HESocketManager

#pragma mark - LifeCycle
+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static HESocketManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[HESocketManager alloc] init];
        instance.delegateList = [NSPointerArray weakObjectsPointerArray];
    });
    return instance;
}

- (void)addDelegate:(id<HESocketManagerDelegate>)delegate {
    [self.delegateList addPointer: (__bridge void * _Nullable)delegate];
}

- (void)removeDelegate:(id<HESocketManagerDelegate>)delegate {
    [[self.delegateList allObjects] enumerateObjectsUsingBlock:^(id<HESocketManagerDelegate> _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj == delegate) {
            [self.delegateList removePointerAtIndex:idx];
            *stop = YES;
        }
    }];
}

- (void)removeAllDelegate {
    //先数组中添加一个NULL 才能清空数组
    [self.delegateList addPointer:NULL];
    [self.delegateList compact];
}

#pragma mark - method
- (void)connect {
    self.circleChatManager = [HECircleChatManager sharedManager];

    
    // 关闭socket
    [self close];
    
    NSURL *url = [NSURL URLWithString:@"wss://www.honglutec.com"];
//    NSURL *url = [NSURL URLWithString:@"wss://192.168.1.135:3000"];
//    NSURL *url = [NSURL URLWithString:@"wss://www.honglutec.com:3000"];
//        NSURL *url = [NSURL URLWithString:@"ws://121.37.24.200:3000"];


    
    UserInfo *userInfo = [[UserManager sharedUserManager] getUserInfo];
    
    NSString *name = [DYTools isBlankString:userInfo.nickname] ? userInfo.username : userInfo.nickname;
 
    NSDictionary *dic = @{@"token" : [[UserManager sharedUserManager] getToken], @"usid" : userInfo.id, @"realname" : name};

    _manger = [[SocketManager alloc] initWithSocketURL: url config:@{@"log": @NO, @"forcePolling": @NO, @"secure": @NO,  @"connectParams":dic}];
    _socket = _manger.defaultSocket;
 
    /** 防止重复监听 */
 
    // 登录成功回调
    [_socket on:@"online" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSLog(@"连接成功...");
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(loginSuccessHandler)]) {
                [delegate loginSuccessHandler];
            }
        }
     }];
 
    // 私人聊天消息回调
    [_socket on: @"imMessage" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        DLog(@"%@", [msgDict mj_JSONString])
        HEIMInfoEntity *entitiy = [HEIMInfoEntity mj_objectWithKeyValues:msgDict];
        NSArray *meassageArr = [HEIMForward transformIMModel:@[entitiy]];
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onRecvMessages:)]) {
                [delegate onRecvMessages:meassageArr.firstObject];
            }
        }
    }];
    
    // 团队聊天消息回调
    [_socket on: @"teamMsg" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        HEIMInfoEntity *entitiy = [HEIMInfoEntity mj_objectWithKeyValues:msgDict];
        NSArray *meassageArr = [HEIMForward transformIMModel:@[entitiy]];
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onRecvMessages:)]) {
                [delegate onRecvMessages:meassageArr.firstObject];
            }
        }
    }];
    
    // 图文聊天消息回调
    [_socket on: @"twMessage" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
 
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        HEDocImMsgModel *entitiy = [HEDocImMsgModel mj_objectWithKeyValues:msgDict];
        
        NSArray *meassageArr = [HEIMForward transformTWModel:@[entitiy]];
        HEIMMessageModel *model = meassageArr.firstObject;
        model.message.refrenceId = entitiy.inst_id;
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onRecvMessages:)]) {
                [delegate onRecvMessages: model];
            }
        }
    }];
 
    [_socket on:@"error" callback:^(NSArray * data, SocketAckEmitter * ack) {
           NSLog(@"连接异常");
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onErrorHandler)]) {
                [delegate onErrorHandler];
            }
        }
     }];
    
    [_socket on:@"disconnect" callback:^(NSArray * data, SocketAckEmitter * ack) {
        NSLog(@"断开连接");
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onDisConnectHandler)]) {
                [delegate onDisConnectHandler];
            }
        }
     }];
    
    KWeakSelf
    // 实时获取聊天室人数新增、删除信息
    [_socket on: @"chatRoomUp" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        [weakSelf.circleChatManager chatRoomUpHandler: msgDict];
    }];
    
    // 实时获取聊天室消息
    [_socket on: @"chatRoomMsg" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        [weakSelf.circleChatManager chatRoomMsgHandler: msgDict];
    }];
    
    // 实时获取聊天室列表新增、删除数据
    [_socket on: @"chatRoomListUp" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        [weakSelf.circleChatManager chatRoomListUpHandler: msgDict];
    }];
    
    
    // 群聊天消息回调
    [_socket on: @"groupRoomMsg" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        HEIMInfoEntity *entitiy = [HEIMInfoEntity mj_objectWithKeyValues:msgDict];
        NSArray *meassageArr = [HEIMForward transformIMModel:@[entitiy]];

        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onRecvMessages:)]) {
                [delegate onRecvMessages:meassageArr.firstObject];
            }
        }
    }];
    
    // 群聊人员更新
    [_socket on: @"groupsMsg" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onGroupMemberUpdate:)]) {
                [delegate onGroupMemberUpdate: msgDict];
            }
        }
    }];
    
    // 群聊人员创建/删除
    [_socket on: @"groupRoomListUp" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSDictionary *msgDict = (NSDictionary *)[data objectAtIndex:0];
        for (id<HESocketManagerDelegate> delegate in self.delegateList) {
            if ([delegate respondsToSelector:@selector(onGroupCreateAndDelUpdate:)]) {
                [delegate onGroupCreateAndDelUpdate: msgDict];
            }
        }
    }];
    
    [_socket connect];
}

- (void)close {
    if (_socket) {
        [_socket disconnect];
        [_socket removeAllHandlers];
    }
    
    [self removeAllDelegate];
}



@end
